/*************************************************
 * 
 * Copyright by Bruno Eberhard
 * 
 * Created on 02.01.2006
 *
 *************************************************/
package fightplan.persistence;

import static fightplan.persistence.ImportHelper.getString;

import java.io.File;
import java.io.FileInputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import fightplan.business.Category;
import fightplan.business.Dojo;
import fightplan.business.Fighter;
import fightplan.business.Team;
import fightplan.business.Tournament;

public class ExcelSkrImport {

	static void imprtFightersAndTeams(Tournament tournament, File file) throws Exception {
		POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
		HSSFWorkbook wb = new HSSFWorkbook(fs);

		HSSFSheet sheet = wb.getSheetAt(0);

		// ////////////////////////////////////////////////
		// if (!checkSheet(sheet, (short)0, (short)36, "Format 080315")) throw
		// new IllegalArgumentException("Kein gültiges Excelsheet: " +
		// file.getName());
		if (findMiddle(sheet) < 0)
			throw new IllegalArgumentException("Kein gültiges Excelsheet: " + file.getName());

		// Dojo
		String dojoName = getString(sheet.getRow(2), 1);
		Dojo dojo = tournament.getOrCreateDojo(dojoName);

		// read Fighters
		readFighters(tournament, dojo, sheet);

		// read Teams
		readTeams(tournament, dojo, sheet);
	}

	// sucht nach dem Text "Startgelder" von oben herab.
	// damit wird die Trennung zwischen einzel und team bestimmt
	private static int findMiddle(HSSFSheet sheet) {
		return findText(sheet, "Startgelder");
	}

	private static int findText(HSSFSheet sheet, String text) {
		int i = 0;
		while (i < 1000) {
			HSSFRow row = sheet.getRow(i);
			if (row != null) {
				String s = getString(row, 0);
				if (s != null && s.startsWith(text)) {
					break;
				}
			}
			i++;
		}
		return i != 1000 ? i : -1;
	}

	private static void readFighters(Tournament tournament, Dojo dojo, HSSFSheet sheet) {
		int middle = findMiddle(sheet);
		for (int i = 6; i < middle; i++) {
			HSSFRow row = sheet.getRow(i);
			if (row == null)
				continue;
			String fighterName = getString(row, 0);
			if (fighterName == null || fighterName.length() == 0)
				continue;

			fighterName = ImportHelper.normalizeName(fighterName);

			Fighter fighter = new Fighter();
			fighter.setName(fighterName);
			fighter.setDojo(dojo);

			try {
				fighter.setYearFormatted(getString(row, 3));
			} catch (IllegalArgumentException iae) {
				// silent
			}

			String kyuString = getString(row, 4);
			if (kyuString != null && kyuString.length() > 0 && Character.isDigit(kyuString.charAt(0))) {
				fighter.setBelt(-Integer.parseInt(kyuString.substring(0, 1)));
			}

			String weightString = getString(row, 5);
			if (weightString != null) {
				try {
					fighter.setWeightFormatted(weightString);
				} catch (IllegalArgumentException iae) {
					// silent
				}
			}

			for (int j = 0; j <= 33; j++) {
				String x = getString(row, j + 6);
				if (x == null || x.length() == 0)
					continue;

				for (Category category : tournament.getCategories()) {
					if (category.getCategoryId() == j) {
						fighter.setGender(category.getGender());
						category.getFighters().add(fighter);
					}
				}
			}

			tournament.getFighters().add(fighter);
		}
	}

	private static boolean checkSheet(HSSFSheet sheet, short rowNr, short cellNr, String format) {
		if (sheet == null)
			return false;

		HSSFRow row = sheet.getRow(rowNr);
		if (row == null)
			return false;

		HSSFCell cell = row.getCell(cellNr);
		if (cell == null)
			return false;

		String s = cell.getStringCellValue();
		if (s == null)
			return false;

		return format.equals(s);
	}

	private static void readTeams(Tournament tournament, Dojo dojo, HSSFSheet sheet) {
		int middle = findMiddle(sheet);

		for (int i = 0; i <= 5; i++) {
			HSSFRow row = sheet.getRow(middle + 2 + i);
			String anzahlString = getString(row, 5);
			if (anzahlString == null || anzahlString.length() == 0)
				continue;

			int anzahl = Integer.parseInt(anzahlString);
			if (anzahl == 0) {
				continue;
			}

			Category category = null;
			for (Category c : tournament.getCategories()) {
				if (c.getCategoryId() == 34 + i) {
					category = c;
					break;
				}
			}

			if (anzahl == 1) {
				Team team = new Team();
				team.setDojo(dojo);
				team.setCategory(category);
				category.addFighter(team);
			} else {
				for (int j = 0; j < anzahl; j++) {
					Team team = new Team();
					team.setDojo(dojo);
					team.setCategory(category);
					team.setNumber(j + 1);
					category.addFighter(team);
				}
			}
		}
	}

}
